package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"net"
	"net/http"
	"net/rpc"
	"net/url"
	"os"
	"strconv"
	"time"
)

const reqtimes = 50

type Node struct {
	Id    int
	Num   bool
	Table map[string]string
}

func linkhttp() {
	for i := 0; i < reqtimes; i++ {
		time.Sleep(100 * time.Millisecond)
		msg := "test" + strconv.Itoa(i)
		res, err := http.PostForm("http://127.0.0.1:8234/tpost", url.Values{"message": {msg}})
		if err != nil {
			fmt.Println("连接失败：", err.Error())
			return
		}
		defer res.Body.Close()
	}

}

func intToBytes(n int) []byte {
	data := int64(n)
	bytebuf := bytes.NewBuffer([]byte{})
	binary.Write(bytebuf, binary.BigEndian, data)
	return bytebuf.Bytes()
}

func linktcp() {
	for i := 0; i < 1; i++ {
		conn, err := net.Dial("tcp", "127.0.0.1:8235")
		if err != nil {
			log.Println("connect error", err)
			return
		}
		msg := []byte(strconv.Itoa(i))
		_, err = conn.Write(msg)
		if err != nil {
			log.Fatal(err)
		}
		conn.Close()
	}
	//conn.Close()
}

// func linkrpchttp() {
// 	for i := 0; i < reqtimes; i++ {
// 		time.Sleep(100 * time.Millisecond)
// 		msg := "test" + strconv.Itoa(i)
// 		client, err := rpc.DialHTTP("tcp", "127.0.0.1:8236")
// 		if err != nil {
// 			log.Fatal("dialing:", err)
// 		}
// 		ret := false
// 		client.Call("Raft.Link", msg, &ret)
// 		if !ret {
// 			fmt.Println("raftlink failed1")
// 		}
// 	}
// }

func linkrpctcp() {
	for i := 0; i < 1; i++ {
		time.Sleep(100 * time.Millisecond)
		msg := "t" + strconv.Itoa(i)

		client, err := rpc.Dial("tcp", "127.0.0.1:8237")
		if err != nil {
			log.Fatal("dialing:", err)
		}
		node := new(Node)
		fmt.Println("地址：", &node)
		client.Call("Raft.Link", msg, &node)

		fmt.Println(node.Id, node.Table, node.Num)

	}
}

// 客户端请求文件下载
func testFileRecv() {
	conn, err := net.Dial("tcp", "127.0.0.1:8235")
	if err != nil {
		log.Println("connect error", err)
		return
	}
	_, err = conn.Write([]byte("Download"))
	if err != nil {
		log.Fatal(err)
	}
	/**
	  读取文件名，向文件发送者返回OK
	*/
	buf := make([]byte, 4096)
	n, err := conn.Read(buf)
	if err != nil {
		fmt.Println("conn.Read err:", err)
		return
	}
	filename := string(buf[:n])
	fmt.Println("filename:", filename)
	if filename != "" {
		_, err = conn.Write([]byte("ok"))
		if err != nil {
			fmt.Println("conn.Write err:", err)
			return
		}
	} else {
		return
	}
	/**
	  创建文件并写入文件内容
	*/
	fmt.Println(filename)
	file, err := os.Create(filename)
	if err != nil {
		fmt.Println("os.Create err:", err)
		return
	}

	for {
		n, err := conn.Read(buf)
		if n == 0 {
			fmt.Println("文件读取完毕")
			break
		}
		if err != nil {
			fmt.Println("conn.Read err:", err)
			return
		}
		file.Write(buf[:n])
	}
}

func mai44n() {
	testFileRecv()
}

func main() {
	if os.Args[1] == "1" {
		t0 := time.Now()
		linkhttp()
		t1 := time.Now()
		fmt.Println("耗时：", t1.Sub(t0)-time.Duration(5)*time.Second)
	}
	if os.Args[1] == "2" {
		t0 := time.Now()
		linktcp()
		t1 := time.Now()
		fmt.Println("耗时：", t1.Sub(t0))
	}
	// if os.Args[1] == "3" {
	// 	t0 := time.Now()
	// 	linkrpchttp()
	// 	t1 := time.Now()
	// 	fmt.Println("耗时：", t1.Sub(t0)-time.Duration(5)*time.Second)
	// }
	if os.Args[1] == "4" {
		t0 := time.Now()
		linkrpctcp()
		t1 := time.Now()
		fmt.Println("耗时：", t1.Sub(t0)-time.Duration(5)*time.Second)
	}
}

/*
func sendPost2() {
	apiUrl := "http://127.0.0.1"
	resource := "/tpost"
	data := url.Values{}
	data.Set("name", "rnben")

	u, _ := url.ParseRequestURI(apiUrl)
	u.Path = resource
	urlStr := u.String() // "http://127.0.0.1/tpost"

	client := &http.Client{}
	r, _ := http.NewRequest("POST", urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

	resp, err := client.Do(r)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer resp.Body.Close()
	fmt.Println("post send success")

}

func sendjsonMsg() {
	postmsg := make(map[string]interface{})
	postmsg["clientID"] = "ahuhwi"
	postmsg["operation"] = "GetMyname"
	postmsg["timestamp"] = time.Now().Unix()

	bytesData, err := json.Marshal(postmsg)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	reader := bytes.NewReader(bytesData)
	url := "http://127.0.0.1:8070/tpost"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	str := (*string)(unsafe.Pointer(&respBytes))
	fmt.Println(*str)
}

func main() {
	var t0 time.Time
	t0 = time.Now()
	sendPost1()
	//sendjsonMsg()
	t1 := time.Now()
	fmt.Println(t1.Sub(t0) - time.Duration(10)*time.Second)
	//sendPost2()
}
*/
